package com.beiben.system.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.beiben.ability.people.domain.TreeSelectDept;
import com.beiben.system.group.service.IGroupService;
import com.beiben.system.hours.domain.UserHours;
import com.beiben.system.hours.service.IHoursService;
import com.beiben.system.hours.service.IUserHoursService;
import com.beiben.system.user.domain.BeiBenUser;
import com.beiben.system.user.domain.TreeSelectVo;
import com.beiben.system.user.domain.UserTreeSelect;
import com.beiben.system.user.service.IBeiBenUserService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by admin on 2020/8/25.
 */

@RestController
@RequestMapping("/beiben/system/user")
public class UserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IBeiBenUserService beiBenUserService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IHoursService hoursService;

    @Autowired
    private IUserHoursService userHoursService;

    @Autowired
    private IGroupService groupService;




    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(BeiBenUser user)
    {
        startPage();
        List<BeiBenUser> list = beiBenUserService.selectBeiBenUserList(user);
        return getDataTable(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getUserInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        ajax.put("hours",  hoursService.selectHoursAll());
        ajax.put("groupTypes",  groupService.selectGroupAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, beiBenUserService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
            ajax.put("hoursIds", hoursService.selectUserHours(userId));
            ajax.put("groupTypeIds", groupService.selectUserGroup(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody BeiBenUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setHoursIds(user.getHoursIds());
        int result = beiBenUserService.insertBeiBenUser(user);
        return toAjax(result);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody BeiBenUser user)
    {
        userHoursService.deleteUserHoursById(user.getUserId());
        UserHours userHours = new UserHours();
        userHours.setUserId(user.getUserId());
        userHours.setHoursId(Long.valueOf(user.getHoursIds()));
        userHoursService.insertUserHours(userHours);
        beiBenUserService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(beiBenUserService.updateBeiBenUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        userHoursService.deleteUserHoursByIds(userIds);
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 根据部门编号获取部门人员及部门详细信息
     */
    @GetMapping(value = "/dept/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        List<TreeSelectDept> data = beiBenUserService.buildDeptTreeSelect(deptId);
        return AjaxResult.success(data);
    }


    /**
     * 根据部门编号获取部门人员详细信息
     */
    @GetMapping(value = "/dept/user/{deptId}")
    public AjaxResult getDeptUserInfo(@PathVariable Long deptId)
    {
        List<BeiBenUser> data = beiBenUserService.getDeptUserInfo(deptId);
        return AjaxResult.success(data);
    }

    /**
     * 根据部门编号获取部门人员数
     */
    @GetMapping(value = "/dept/tree/user")
    public AjaxResult getDeptUserTreeInfo(SysDept dept)
    {
        List<TreeSelectVo>  userList = beiBenUserService.buildUserTreeSelect(100);
        return AjaxResult.success(userList);
    }

}
